import {useUserStore} from "@/store/user";
import {useMenuStore} from "@/store/menu";
import {notification} from '@/hooks/modules/useMessage'
import request from "@/service/request";

export const usePermissions = () => {
    const {setUserInfo, setAuthPermission, setAuthRole, signOut} = useUserStore()
    const {setAuthMenuList} = useMenuStore()

    const initPermissions = async (token: string) => {
        if (!token) return
        try {
            const {data: userInfo} = await request.post('/user') as unknown as Record<string, any>
            setUserInfo(userInfo)
            setAuthPermission(userInfo)
            setAuthRole(userInfo)

            const {data: authMenuList} = await request.post('/menus') as unknown as Record<string, any>
            setAuthMenuList(authMenuList)

            if (!authMenuList.length) {
                notification.warning({
                    message: "无权限访问",
                    description: "当前账号无任何菜单权限，请联系系统管理员！"
                });
                signOut()
                window.$navigate('/login', {replace: true})
                return Promise.reject("No permission");
            }
        } catch (e) {
            notification.warning({
                message: "无权限访问",
                description: "当前账号获取菜单或角色接口出现异常，请联系系统管理员！"
            });
            signOut()
            window.$navigate('/login', {replace: true})
            return Promise.reject("No permission");
        }
    }

    return {initPermissions}
}
